<?php defined('SYSPATH') or die('No direct script access.');

class HTTP_Exception extends Kohana_HTTP_Exception {
 
    /**
     * Generate a Response for all Exceptions without a more specific override
     * 
     * The user should see a nice error page, however, if we are in development
     * mode we should show the normal Kohana error page.
     * 
     * @return Response
     */
    public $_config;
    public $lang = 'ru';
    public $postfix;
    public $title;
    public $description;
    public $sitetext;

    public function prepare_page() {
        $this->_config = Kohana::$config->load('main');

        if (!Request::initial()->param('lang') || Request::initial()->param('lang') == 'ru') {
            $this->lang = 'ru';
        } else {
            $this->lang = Request::initial()->param('lang');
            $this->postfix = '_'.$this->lang;
        }

        $this->sitetext = ORM::factory('Sitetext')->getAll($this->postfix);
        $this->title = $this->sitetext['comapny_name']['_value'].' - 404';
        $this->description = $this->sitetext['meta_description']['_value'];
    }

    public function get_response()
    {
        // Lets log the Exception, Just in case it's important!
        Kohana_Exception::log($this);
 
        if (Kohana::$environment >= Kohana::DEVELOPMENT)
        {
            // Show the normal Kohana error page.
            return parent::get_response();
        }
        else
        {
            $this->prepare_page();

            $view = View::factory('layout/error', array(
                'title' => $this->title,
                'header' => View::factory('pieces/header', array(
                    'lang' => $this->lang,
                    'sitetext' => $this->sitetext,
                    'menu' => ORM::factory('Menu')->getAll($this->postfix),
                    'menu_count' => ORM::factory('Menu')->count_all(),
                    'c_url' => $c_uri = Request::detect_uri()
                )),
                'content' => View::factory('errors/404', array('message' => $this->getMessage())),
                'footer' => View::factory('pieces/footer', array('sitetext' => $this->sitetext)),
            ));
 
            $response = Response::factory()
                ->status($this->getCode())
                ->body($view->render());
 
            return $response;
        }
    }
}